<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path;
	//String soketPath = "192.168.31.62" + ":" + request.getServerPort() + path;
	//String soketPath = "119.23.36.128:8020" + path;
	String soketPath = "39.108.99.234:" + request.getServerPort() + path;
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
<title>私信留言-云校通</title>
<link rel="stylesheet" href="<%=basePath %>/style/messages.css"/>
<jsp:include page="/WEB-INF/page/common/_header.jsp"></jsp:include>
</head>
<body ontouchstart style="background: #FFFFFF;">
	<div class="weui-header" style="border-bottom: 1px solid #f7d6d6;padding:0;font-size: 14px;position: fixed;top: 0;background: #f9f5f5;z-index: 600;width: 100%;"> 
		<div class="weui-header-left" style="line-height: 15px;"><a href="<%=basePath %>${user.currUrl}/message<c:if test='${user.roleType == 0 }'>?sid=${user.parent.studentId }</c:if>" class="icon icon-109 f-black"></a></div>
		<h1 class="weui-header-title f-black" style="font-size: 14px;">
			<c:choose>
				<c:when test="${user.roleType == 1 }">${studentName}家长</c:when>
				<c:otherwise>${studentName}的老师</c:otherwise>
			</c:choose>私信留言
		</h1>
	</div>
    <div class="weui_panel weui_panel_access" style="margin-top: 40px;margin-bottom: 55px;">
	    <div class="weui_tab_bd" id="tab_bd" style="padding-bottom: 40px;">
           	<div class="weui_panel_bd page-content messages-content" style="overflow: scroll;">
				<div class="messages messages-auto-layout" id="message-content">
				</div>
			</div>
		</div>
    </div>
	<div class="weui_tabbar" style="position: fixed;">
        <div class="toolbar messagebar">
			<div class="toolbar-inner">
				<a href="javascript:" class="link icon-only"><i class="icon icon-77 f31"></i>
					<input class="weui_uploader_input" type="file" max="2" accept="image/jpg,image/jpeg,image/png,image/gif" id="image-message" multiple>
				</a>
				<textarea placeholder="想说点什么~" id="message"></textarea>
				<a href="javascript:;" id="text-submit" class="weui_btn weui_btn_mini weui_btn_default">发送</a><!--输入有内容时把default改为primary-->
			</div>
		</div>
    </div>
	<script type="text/javascript">
		//页数 
	    var page = 1;
	    // 每页展示10个
	    var size = 20;
	    var chatType = 'private';
	    var userRole = "${user.roleType}";
	    var grade = "${grade}";
	    var clazz = "${clazz}";
	    var studentId = "${studentId}";
	    var studentName = "${studentName}";
	    var schoolId = userRole == '0' ? "${user.parent.schoolId}" : "${user.teacher.schoolId}";
	    var startDate = getTime(new Date(), 'yyyy-MM-dd hh:mm:ss');
		var prevTime;
		var websocket = null;
		privateChatCache(userRole, schoolId, chatType, grade, clazz, studentId, studentName);
		//判断当前浏览器是否支持WebSocket  
	    if ('WebSocket' in window) {
	    	var userRole = "${user.roleType}";
	    	var userId = userRole == '0' ? "${user.parent.id}" : "${user.teacher.id}";
	    	var userName = userRole == '0' ? "${user.parent.name}" : "${user.teacher.name}";
	    	var headImgUrl = userRole == '0' ? "${user.parent.headImgUrl}" : "${user.teacher.headImgUrl}";
	        websocket = new WebSocket("ws://<%=soketPath%>/websocket/privateLetter?userRole=" + userRole + "&userId=" + userId + "&userName=" + userName + "&headImgUrl=" + headImgUrl + "&grade=" + grade + "&clazz=" + clazz + "&studentId=" + studentId);  
	    }
	    //接收到消息的回调方法  
	    websocket.onmessage = function (event) {  
	    	var obj = JSON.parse(event.data);
	    	loadSendHtml(obj);
	    }  
	    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。  
	    window.onbeforeunload = function () {  
	    	var obj = $(".message-text:last");
	    	if(obj.length == 0) return;
	    	var length = obj.find('img').length;
	    	var message = length > 0 ? "[图片]" : obj.text();
	    	changeprivateChatValue(userRole, schoolId, chatType, grade, clazz, studentId, prevTime, message)
	    	websocket.close();  
	    }
	    $(function(){
	    	loadItem();
	    	var isOver = false;
		    $('.weui_panel').dropload({
		        scrollArea : window,
		        autoLoad : true,//自动加载
		        domDown : {//上拉
		            domClass   : 'dropload-down',
		            domRefresh : '<div class="dropload-refresh f15 "><i class="icon icon-20"></i>上拉加载更多</div>',
		            domLoad    : '<div class="dropload-load f15"><span class="weui-loading"></span>正在加载中...</div>',
		            domNoData  : '<div class="dropload-noData">没有更多数据了</div>'
		        },
		        domUp : {//下拉
		            domClass   : 'dropload-up',
		            domRefresh : '<div class="dropload-refresh"><i class="icon icon-114"></i>上拉加载更多</div>',
		            domUpdate  : '<div class="dropload-load f15"><i class="icon icon-20"></i>松手开始加载...</div>',
		            domLoad    : '<div class="dropload-load f15"><span class="weui-loading"></span>正在加载中...</div>'
		        },
		        loadUpFn : function(me){//加载更多
		        	var params = {
	    				page: page,
	    	  	 		rows: size,
	    	  	 		grade: grade,
	    	  	 		clazz: clazz,
	    	  	 		studentId: studentId,
	    	  	 		startDate: startDate,
	    	  	 		schoolId: schoolId
	    			};
	    			$.ajax({
	    	          	url : basePath + "/groupChat/class/page/query",
	    	  	 		type : "post",
	    	  	 		dataType : "json",
	    	  	 		data : params,
	    	            success: function(data){
	             		  if(data.rows.length == 0 || page*size >= data.total) {// 如果没有数据
	                          if(isOver){
	                        	  me.lock();
	 	             			  me.resetload();
	                        	  return;
	                          }
	             			  isOver = true;
	                      }
	             		  page++;
	             		  setTimeout(function(){
		                      loadGroupChatHtml(data);
		                      // 每次数据加载完，必须重置
		                      me.resetload();
		                      // 解锁
		                      me.unlock();
		                      me.noData(false);
	             		  },200);
	             		  if(isOver) {
	             			 me.lock();
	             			 me.resetload();
	             			 return;
	             		  }
	                  },
	                  error: function(xhr, type){
	                  }
	              });      
		        }
		    });
		    document.querySelector('#image-message').onchange = function(e) {
				var files = e.target.files;
				var len = files.length;
				for (var i=0; i < len; i++) {
					lrz(files[i], {
						width:1080
					})
					.then(function (rst) {
						var currTime = new Date().getTime();
						var xhr = new XMLHttpRequest();
			            xhr.open('POST', basePath + "${user.currUrl}/groupChat/class/online");
			            xhr.onload = function () {
			            	var data = JSON.parse(xhr.response);
			                if (data.code == '000') {
			                	var obj = {messageType: 'image', message: data.data.message};
			                	var headImgUrl = "";
			                	if("${user.roleType}" == "0") {
			                		headImgUrl = "${user.parent.headImgUrl}";
			                	}else {
			                		headImgUrl = "${user.teacher.headImgUrl}";
			                	}
			                	var html = "";
			                	if(!prevTime) {
					    			prevTime = currTime;
					    			html += '<div class="messages-date">'+getTime(prevTime, 'yyyy年MM月dd日 hh:mm')+'</div>';
					    		}
					    		if(!isCompareTime(prevTime, currTime)) {
					    			prevTime = currTime;
					    			html += '<div class="messages-date">'+getTime(prevTime, 'yyyy年MM月dd日 hh:mm')+'</div>';
					    		}
				            	html += '<div class="message message-sent message-pic message-last message-with-tail" id="id_'+data.data.id+'">';
				    			html += '<div class="message-text"><img src="'+rst.base64+'"/></div>';
				    			html += '<div style="background-image:url(${config.imgUrl}'+headImgUrl+')" class="message-avatar"></div></div>';
				    			$(html).appendTo($("#message-content"));
				    			$("#id_"+data.data.id + " img")[0].addEventListener('click', imgClickEvent);
				    			getSelectPos();
				    			websocket.send(JSON.stringify(obj));
			                }
			            };
			            xhr.onerror = function () {
			            	alert("上传异常");
			            };
			            xhr.upload.onprogress = function (e) {
			                // 上传进度
			                var percentComplete = ((e.loaded / e.total) || 0) * 100;
			            };
			            // 添加参数
			            rst.formData.append('grade', grade);
			            rst.formData.append('clazz', clazz);
			            rst.formData.append('studentId', studentId);
			            rst.formData.append('imageName', rst.origin.name);
			            rst.formData.append('baseData', rst.base64);
			            rst.formData.append('messageType', "image");
			            rst.formData.append('chatType', "private");
			            // 触发上传
			            xhr.send(rst.formData);
			            return rst;
					})
			        .always(function () {
			            // 不管是成功失败，都会执行
			        });
					;
				}
			}
		    $("#text-submit").click(function() {
		    	var message = $("#message").val().trim();
		    	if(message == '') return;
		    	if(message.length > 2000) {
		    		alert("超过了2千的字符！");
		    		return;
		    	}
		    	var currTime = new Date().getTime();
		    	$.ajax({
		          	url : basePath + "${user.currUrl}/groupChat/class/online",
		  	 		type : "post",
		  	 		dataType : "json",
		  	 		data : {
		  	 			grade: grade,
			  	 		clazz: clazz,
			  	 		studentId: studentId,
		  	 			messageType: 'text',
		  	 			chatType: 'private',
		  	 			message: message
		  	 		},
		            success: function(data){
		            	if(data.code == '000') {
		            		var obj = {messageType: 'text', message: data.data.message};
		            		$("#message").val('');
		            		var headImgUrl = "";
		                	if("${user.roleType}" == "0") {
		                		headImgUrl = "${user.parent.headImgUrl}";
		                	}else {
		                		headImgUrl = "${user.teacher.headImgUrl}";
		                	}
			         		var html = "";
			         		if(!prevTime) {
				    			prevTime = currTime;
				    			html += '<div class="messages-date">'+getTime(prevTime, 'yyyy年MM月dd日 hh:mm')+'</div>';
				    		}
				    		if(!isCompareTime(prevTime, currTime)) {
				    			prevTime = currTime;
				    			html += '<div class="messages-date">'+getTime(prevTime, 'yyyy年MM月dd日 hh:mm')+'</div>';
				    		}
			    			html += '<div class="message message-sent message-last message-with-tail" id="id_'+data.data.id+'">';
			    			html += '<div class="message-text">'+message+'</div>';
			    			html += '<div style="background-image:url(${config.imgUrl}'+headImgUrl+')" class="message-avatar"></div></div>';
			    			$(html).appendTo($("#message-content"));
			    			getSelectPos();
			    			websocket.send(JSON.stringify(obj));
		            	}
		            },
	                error: function(xhr, type){
	                  
	                }
		          });
		    });
	    });
	    function loadSendHtml(data) {
	    	var currTime = new Date().getTime();
	    	var html = "";
	    	if(data.user) {
	    		if(!prevTime) {
	    			prevTime = currTime;
	    			html += '<div class="messages-date">'+getTime(prevTime, 'yyyy年MM月dd日 hh:mm')+'</div>';
	    		}
	    		if(!isCompareTime(prevTime, currTime)) {
	    			prevTime = currTime;
	    			html += '<div class="messages-date">'+getTime(prevTime, 'yyyy年MM月dd日 hh:mm')+'</div>';
	    		}
	    		if(data.messageType == 'image') {
					html += '<div class="message message-received message-pic message-with-avatar message-last message-with-tail message-first" id="id_'+currTime+'">';
					html += '<div class="message-name">'+data.user.userName+'</div>';
					html += '<div class="message-text"><a href="javascript:"><img src="${config.imgUrl}'+data.message+'"></a></div>';
					html += '<div style="background-image:url(${config.imgUrl}/'+data.user.headImgUrl+')" class="message-avatar"></div></div>';
				}else if(data.messageType = 'text') {
					html += '<div class="message message-received message-with-avatar message-last message-with-tail message-first">';
					html += '<div class="message-name">'+data.user.userName+'</div>';
					html += '<div class="message-text">'+data.message+'</div>';
					html += '<div style="background-image:url(${config.imgUrl}/'+data.user.headImgUrl+')" class="message-avatar"></div></div>';
				}
	    	}else {
	    		html += '<div class="messages-date">'+ data.message +'</div>';
	    	}
			$(html).appendTo($("#message-content"));
			if(data.messageType == 'image') {
				$("#id_"+ currTime + " img")[0].addEventListener('click', imgClickEvent);
			}
			getSelectPos();
	    }
	    function loadItem() {
	    	var params = {
   				page: page,
   	  	 		rows: size,
   	  	 		grade: grade,
   	  	 		clazz: clazz,
   	  	 		studentId: studentId,
   	  	 		startDate: startDate,
   	  	 		chatType: 'private',
   	  	 		schoolId: schoolId
   			};
   			$.ajax({
   	          	url : basePath + "/groupChat/class/page/query",
   	  	 		type : "post",
   	  	 		dataType : "json",
   	  	 		data : params,
   	            success: function(data){
            		 page++;
                     loadGroupChatHtml(data);
                     img_click();
                     getSelectPos();
                 },
                 error: function(xhr, type){
                     
                 }
             });
	    }
	    function loadGroupChatHtml(data) {
	    	if(data == null) return;
	    	var html = "";
	    	var lenth = data.rows.length - 1;
	    	for(var i in data.rows) {
	    		var row = data.rows[lenth - i];
	    		if(row.studentId != null) {
	    			row.name = row.name + "的家长";
	    		}
	    		if(!prevTime) {
	    			prevTime = row.createTime;
	    			html += '<div class="messages-date">'+getTime(prevTime, 'yyyy年MM月dd日 hh:mm')+'</div>';
	    		}
	    		if(!isCompareTime(prevTime, row.createTime)) {
	    			prevTime = row.createTime;
	    			html += '<div class="messages-date">'+getTime(prevTime, 'yyyy年MM月dd日 hh:mm')+'</div>';
	    		}
	    		if(parseInt("${user.parent.id}") == row.userId || parseInt("${user.teacher.id}") == row.userId) {
	    			if(row.messageType == 'image') {
	    				html += '<div class="message message-sent message-pic message-last message-with-tail" id="id_'+row.id+'">';
		    			html += '<div class="message-text">';
		    			html += '<a href="javascript:"><img src="${config.imgUrl}'+row.message+'"></a></div>';
		    			html += '<div style="background-image:url(${config.imgUrl}/'+row.headImgUrl+')" class="message-avatar"></div></div>';
	    			}else {
		    			html += '<div class="message message-sent message-last message-with-tail message-first" id="id_'+row.id+'">';
		    			html += '<div class="message-text">'+row.message+'</div>';
		    			html += '<div style="background-image:url(${config.imgUrl}/'+row.headImgUrl+')" class="message-avatar"></div></div>';
	    			}
	    		}else {
	    			if(row.messageType == 'image') {
	    				html += '<div class="message message-received message-pic message-with-avatar message-last message-with-tail message-first" id="id_'+row.id+'">';
						html += '<div class="message-name">'+row.name+'</div>';
						html += '<div class="message-text"><a href="javascript:"><img src="${config.imgUrl}'+row.message+'"></a></div>';
						html += '<div style="background-image:url(${config.imgUrl}/'+row.headImgUrl+')" class="message-avatar"></div></div>';
	    			}else {
	    				html += '<div class="message message-received message-with-avatar message-last message-with-tail message-first" id="id_'+row.id+'">';
						html += '<div class="message-name">'+row.name+'</div>';
						html += '<div class="message-text">'+row.message+'</div>';
						html += '<div style="background-image:url(${config.imgUrl}/'+row.headImgUrl+')" class="message-avatar"></div></div>';
	    			}
	    		}
	    	}
	    	$("#message-content").prepend(html);
	    	img_click();
	    }
	    function isCompareTime(prevTime, currTime) {
	    	var times = Math.abs(prevTime - currTime);
	    	var minutes = Math.floor(times/(60*1000))
	    	if(minutes >= 9) {
	    		return false;
	    	}
	    	return true;
	    }
	    function img_click() {
	    	$("#message-content img").each(function(i, v) {
	    		v.removeEventListener("click", imgClickEvent, false);
	    		v.addEventListener('click', imgClickEvent);
	    	})
		}
	    function imgClickEvent() {
	    	var obj = $(this.closest("#message-content")).find("img");
			var src = get_img(obj);
			var curent = obj.index(this);
			img_preview(src[curent], src);
	    }
		function img_preview(current, urls){
	        if(!current || urls.length == 0){
		        return ;
	        }

	        WeixinJSBridge.invoke('imagePreview', { 
	            'current': current,
	            'urls': urls
	        }); 
		}
		function get_img(obj){
			var m = [];
			for(var i=0; i<obj.length; i++){
				m[i] = obj[i].src;
			}
			
			return m;
		}
		function getSelectPos(){
			var h = $($(".messages-auto-layout")[0]).scrollHeight()+200;
			window.scrollTo(h,h);
		}
	</script>
</body>
</html>